package web2021.team1.lj.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;
import web2021.team1.lj.domain.User;

import java.sql.ResultSet;
import java.sql.SQLException;




//通过Spring注解定义一个DAO
@Repository
public class UserDao {
    //自动注入JdbcTemplate的Bean
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 获得匹配的用户个数
     * @param username 用户名
     * @param password 密码
     * @return
     */
    public int getMatchCount(String username, String password) {
        String sql = "SELECT count(*) FROM user "
                + " WHERE user_name =? and password=? ";
        return jdbcTemplate.queryForInt(sql, new Object[]{username, password});
    }

    /**
     * 通过用户名查找用户
     * @param username 要查询的用户名
     * @return  找到的用户
     */
    public User findUserByUserName(final  String username) {
        String sqlStr = " SELECT user_id,user_name,password"
                + " FROM user WHERE user_name =? ";
        final User user = new User();
        jdbcTemplate.query(sqlStr, new Object[]{username},
                new RowCallbackHandler() {
                    public void processRow(ResultSet rs) throws SQLException {
                        user.setUserId(rs.getInt("user_id"));
                        user.setUserName(username);
                        user.setPassword(rs.getString("password"));
                    }
                });
        return user;
    }

    /**
     * 更新登录信息
     * @param user 用户
     */
    public void updateLoginInfo(User user) {
        String sqlStr = " UPDATE user SET last_visit=?,last_ip=?"
                + " WHERE user_id =?";
        jdbcTemplate.update(sqlStr, new Object[]{user.getLastVisit(),
                user.getLastIp(), user.getUserId()});
    }

    public void creatUser(String username, String password) {
        String sqlStr = "INSERT INTO user(user_name,password) VALUES ";
        jdbcTemplate.execute(sqlStr + "(\'" + username + "\',\'" + password + "\')");
    }
}
